#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/08/12
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask_security import RoleMixin
from project.flasky import db
from project.define import db_logger, PermissionsModule


class Role(RoleMixin, db.Model):
    """
    角色权限表
    """
    __tablename__ = 'app_role'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 权限名称
    Name = db.Column(db.String(32), nullable=False, unique=True)
    # 默认权限
    Default = db.Column(db.Boolean, default=False)
    # 权限描述
    Description = db.Column(db.String(64))
    # 权限值
    Permissions = db.Column(db.Integer)
    # 关系
    Users = db.relationship('User', backref='app_role', lazy='dynamic')
    # 删除状态
    Deleted = db.Column(db.Boolean, default=False)

    def __init__(self, **kwargs):
        """
        实例参数
        """
        super(Role, self).__init__(**kwargs)
        self.Name = kwargs.get('Name')
        self.Description = kwargs.get('Description')
        self.Permissions = 0

    def to_dict(self):
        """
        获取键值对
        """
        return dict([(c.name, getattr(self, c.name)) for c in self.__table__.columns])

    def update_permission(self, **kwargs):
        """
        更新权限
        """
        self.reset_permission()
        self.Description = kwargs.get('Description')
        permissions = kwargs.get('Permissions')
        for perm in permissions:
            self.add_permission(perm)

    def has_permission(self, perm):
        """
        权限校验
        """
        return self.Permissions & perm == perm

    def add_permission(self, perm):
        """
        添加权限
        """
        self.Permissions += perm

    def remove_permission(self, perm):
        """
        删除权限
        """
        self.Permissions -= perm

    def reset_permission(self):
        """
        重置权限
        """
        self.Permissions = 0

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'id': '權限ID', 'Name': '權限名稱', 'Description': '權限'
            }
        return ColumnName

    @staticmethod
    def roles_info():
        """
        所有权限信息
        """
        roles = Role.query.all()
        return [i.to_dict() for i in roles]

    @staticmethod
    def roles_selections():
        """
        获取选项
        """
        roles = Role.query.all()
        return [{'id':i.id, 'Name': i.Name, 'Description': i.Description} for i in roles]

    @staticmethod
    def table_init():
        """
        插入初始化数据
        """
        roles = PermissionsModule.default_roles
        for i in roles:
            name = i.get('Name')
            row = Role.query.filter_by(Name=name).first()
            if not row:
                row = Role(**i)
                db.session.add(row)
            row.update_permission(**i)
        db_logger.debug(f"app_role：初始化成功！")
        db.session.commit()